import win32com.client
import time


class CANoeController:
    def __init__(self):
        self.canoe_app = None
        self.measurement = None

    def connect_to_canoe(self):
        """连接到CANoe应用程序"""
        try:
            self.canoe_app = win32com.client.Dispatch("CANoe.Application")
            print("成功连接到CANoe")
            return True
        except Exception as e:
            print(f"连接CANoe失败: {e}")
            return False

    def start_measurement(self):
        """启动测量"""
        if self.canoe_app and self.canoe_app.Configuration:
            self.measurement = self.canoe_app.Measurement
            if not self.measurement.Running:
                self.measurement.Start()
                print("测量已启动")
                return True
        print("无法启动测量")
        return False

    def set_high_voltage(self, state):
        """设置高压状态"""
        try:
            # 通过CANoe的CAPL函数或系统变量控制高压
            # 这里假设你有一个名为"HV_Control"的系统变量
            self.canoe_app.System.Namespaces.Item("::").Variables.Item("HV_Control").Value = state
            print(f"高压系统已{'开启' if state else '关闭'}")
            return True
        except Exception as e:
            print(f"控制高压系统失败: {e}")
            return False

    def set_low_voltage(self, state):
        """设置低压状态"""
        try:
            # 通过CANoe的CAPL函数或系统变量控制低压
            # 这里假设你有一个名为"LV_Control"的系统变量
            self.canoe_app.System.Namespaces.Item("::").Variables.Item("LV_Control").Value = state
            print(f"低压系统已{'开启' if state else '关闭'}")
            return True
        except Exception as e:
            print(f"控制低压系统失败: {e}")
            return False

    def stop_measurement(self):
        """停止测量"""
        if self.measurement and self.measurement.Running:
            self.measurement.Stop()
            print("测量已停止")

    def disconnect(self):
        """断开连接"""
        if self.canoe_app:
            self.stop_measurement()
            self.canoe_app = None
            print("已断开与CANoe的连接")


# 使用示例
if __name__ == "__main__":
    canoe = CANoeController()

    if canoe.connect_to_canoe():
        if canoe.start_measurement():
            # 开启低压系统
            canoe.set_low_voltage(True)
            time.sleep(2)  # 等待低压系统稳定

            # 开启高压系统
            canoe.set_high_voltage(True)

            # 保持高压低压运行一段时间
            time.sleep(10)

            # 关闭高压系统
            canoe.set_high_voltage(False)
            time.sleep(2)

            # 关闭低压系统
            canoe.set_low_voltage(False)

            # 停止测量
            canoe.stop_measurement()

        canoe.disconnect()